package com.ak.game.util;

import com.ak.game.exception.ServiceException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Md5加密工具类
 */
public class Md5SignatureUtils {
    /**
     * 生成MD5签名字符串
     *
     * @param content 需要加密的字符串
     * @return MD5签名后的16进制字符串
     */
    public static String generateMd5Sign(String content) {
        try {
            // 获得MD5摘要算法的MessageDigest对象
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 使用指定的字符集将字符串转换成字节数组
            byte[] bytes = content.getBytes("UTF-8");

            // 使用指定的byte数组更新摘要
            md.update(bytes);

            // 获得密文，把密文转换成十六进制的字符串形式
            byte[] digestBytes = md.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte b : digestBytes) {
                hexString.append(String.format("%02x", b & 0xff));
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new ServiceException("10004");
        } catch (java.io.UnsupportedEncodingException e) {
            throw new ServiceException("10004");
        }
    }

    /**
     * 测试main方法：根据sign + gameId + timestamp生成md5
     * @param args
     */
    public static void main(String[] args) {
        String sign = "7b4e6f83920d48d18bc9a6fc56e1a735";
        String gameId = "game_self_3";
        String timestamp = "1719304594086";
        String md5Signature = generateMd5Sign(sign + gameId + timestamp);
        System.out.println("MD5 Signature: " + md5Signature);
    }
}
